<template>
  <div style="width: 68%; margin: 10px auto;">
    <div class="card"  style="padding: 20px">
      <div style="margin-bottom: 20px; font-size: 24px; font-weight: bold">我的帖子</div>
      <div style="margin-bottom: 20px">
          <el-input v-model="data.title" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入帖子标题"></el-input>
          <el-select v-model="data.status" placeholder="请选择帖子状态" style="width: 240px; margin-right: 10px">
              <el-option value="待审核" label="待审核"></el-option>
              <el-option value="审核通过" label="审核通过"></el-option>
              <el-option value="审核拒绝" label="审核拒绝"></el-option>
          </el-select>
          <el-button type="info" plain @click="load">查询</el-button>
          <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
      </div>
      <div style="margin-bottom: 20px">
        <el-table stripe :data="data.tableData">
          <el-table-column prop="image" label="帖子封面" width="100px">
            <template #default="scope">
              <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.image" :preview-src-list="[scope.row.image]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="帖子标题" show-overflow-tooltip width="300px">
            <template #default="scope">
              <div style="cursor: pointer" @click="router.push('/front/postDetail?id=' + scope.row.id)">{{scope.row.title}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="帖子内容" width="120px">
            <template #default="scope">
              <el-button type="primary" @click="view(scope.row.content)">查看内容</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发布时间" show-overflow-tooltip width="180px"></el-table-column>
          <el-table-column prop="viewCount" label="浏览量" width="80px"></el-table-column>
          <el-table-column prop="status" label="审核状态" width="100px">
            <template v-slot="scope">
              <el-tag type="warning" v-if="scope.row.status === '待审核'">待审核</el-tag>
              <el-tag type="success" v-if="scope.row.status === '审核通过'">审核通过</el-tag>
              <el-tag type="danger" v-if="scope.row.status === '审核拒绝'">审核拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" style="margin-left: 20px">
            <template v-slot="scope">
              <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
              <el-button type="danger" circle :icon="Delete" @click="handleDelete(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="data.total">
        <el-pagination
            @current-change="load"
            @size-change="handleSizeChange"
            background layout="total, prev, pager, next, jumper, sizes"
            :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
            :page-size="data.pageSize"
            v-model:current-page="data.pageNum"
            :total="data.total"/>
      </div>
    </div>

    <!--查看内容-->
    <el-dialog title="内容" v-model="data.viewVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <div class="editor-content-view" style="padding: 20px" v-html="data.content"></div>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="data.viewVisible = false">关 闭</el-button>
    </span>
      </template>
    </el-dialog>

    <!--帖子信息-->
    <el-dialog title="帖子信息" v-model="data.formVisible" width="50%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="90px" style="padding: 20px">
        <el-form-item prop="title" label="帖子标题">
          <el-input v-model="data.form.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>
        <el-form-item prop="image" label="帖子图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :headers="{ 'token': data.user.token }"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="content" label="帖子内容">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
                @onChange="handleContentChange"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="update">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
  import {reactive} from "vue";
  import request from "@/utils/request.js";
  import {ElMessage, ElMessageBox} from "element-plus";
  import {Delete, Edit} from "@element-plus/icons-vue";
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import {onBeforeUnmount, ref, shallowRef} from "vue";
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import router from "@/router/index.js";

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    pageNum: 1,
    pageSize: 10,
    title: null,
    status: null,
    tableData: [],
    total: 0,
    content: null,
    viewVisible: false,
    form: null,
    formVisible: false,
    rules: {
      title: [
        { required: true, message: '请输入标题', trigger: ['blur', 'change'] }
      ],
      content: [
        { required: true, message: '请输入内容', trigger: ['blur', 'change'] },
        { validator: (rule, value, callback) => {
            // 去除HTML标签后检查是否有实际内容
            const text = value?.replace(/<[^>]+>/g, '').trim()
            if (!text) {
              callback(new Error('请输入内容'))
            } else {
              callback()
            }
          },
          trigger: ['blur', 'change']
        }
      ],
      image: [
        { required: true, message: '请上传封面', trigger: ['blur', 'change'] }
      ],
    }
  })

  const formRef = ref()

  const baseUrl = import.meta.env.VITE_BASE_URL

  /* wangEditor5 初始化开始 */
  const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
  const mode = 'default'
  const editorConfig = { MENU_CONF: {} }
  // 图片上传配置
  editorConfig.MENU_CONF['uploadImage'] = {
    headers: {
      token: data.user.token,
    },
    server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
    fieldName: 'file'  // 服务端图片上传接口参数
  }
  // 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  // 记录 editor 实例，重要！
  const handleCreated = (editor) => {
    editorRef.value = editor
  }
  /* wangEditor5 初始化结束 */

  // 编辑器内容变化处理
  const handleContentChange = () => {
    // 手动触发内容字段校验
    formRef.value?.validateField('content')
  }


  const handleFileUpload = (res) => {
    data.form.image = res.data
  }

  const load = () => {
    request.post('/post/pageQuery/person', {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
      status: data.status
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  load()

  const reset = () => {
    data.title = null
    data.status = null
    load()
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1
    load()
  }

  const view = (content) => {
    data.content = content
    data.viewVisible = true
  }

  const handleEdit = (row) => {
    data.form = JSON.parse(JSON.stringify(row))
    data.formVisible = true
  }

  // 修改
  const update = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        request.put('/post/update', {
          id: data.form.id,
          title: data.form.title,
          content: data.form.content,
          image: data.form.image
        }).then(res => {
          if (res.code === '200') {
            ElMessage.success('修改成功')
            data.formVisible = false
            load()
          } else {
            ElMessage.error(res.msg)
          }
        })
      } else {
        ElMessage.warning('请输入请填写完')
      }
    })
  }

  const handleDelete = (id) => {
    ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
      request.delete('/post/delete/' + id).then(res => {
        if (res.code === '200') {
          ElMessage.success('删除成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }).catch(err => {
      console.log(err)
    })
  }

</script>